<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax 封装</title>
</head>
<body>
    <button class="get">GET 请求数据</button>
    <button class="post">post 请求数据</button>
    

    <script>
        // ajax  封装
        // promise 铺垫  
        var getbtn = document.getElementsByClassName("get")[0];
        var postbtn = document.getElementsByClassName("post")[0];
        
        // post 请求 
        postbtn.onclick = function(){
            var user = "heelo"
            var pass = "aa"

            // var xhr = new XMLHttpRequest();
            // xhr.open("post","../php/login.php",true)
            // xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            // xhr.send(`user=${user}&pass=${pass}`);
            // xhr.onreadystatechange = function(){
            //     if(xhr.readyState==4 && xhr.status ==200){
            //         var result = JSON.parse(xhr.responseText);
            //         console.log(result)
            //     }
            // }
            post({
                url:"../php/login.php",
                data:{
                    user,
                    pass
                },
                // async:true,
                dataType:"json",
                success:result=>{
                    console.log(result)
                }
            })
        }


        function post(options){
            var {url,data,async=true,dataType="text",success} = options;
            if(data instanceof Object){  // 如果数据是一个对象  循环对象 拼接成字符串 
                var str = "";
                for(var key in data){   // 循环对象 
                    console.log(key,data[key])
                    str += key+"="+data[key]+"&";
                }
                data = str.substring(0,str.length-1);   //字符串截取 
            }
            console.log(data)
            var xhr = new XMLHttpRequest();
            xhr.open("post",url,async);
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");   // 设置请求头的数据类型 
            xhr.send(data);   // 带参数 
            xhr.onreadystatechange = function(){
                if(xhr.readyState==4 && xhr.status ==200){
                    // var result = JSON.parse(xhr.responseText);  不一定所有的返回数据都是 json
                    var result = xhr.responseText;
                    if(dataType=="json"){
                        result = JSON.parse(result);
                    }
                   
                    if(success){
                        success(result)    // 把result 暴露给调用的环境 
                    }
                    
                  
                }
            }
        }
        
        
    </script>
</body>
</html>